import koji, os, sys

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + '../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'riscv_build_dataset.settings')

import django
from django.db.utils import IntegrityError

django.setup()

from fedora.models import koji_package
from config import BASE_URL
from tqdm import tqdm

session = koji.ClientSession(f'{BASE_URL}/kojihub')


def list_packages() -> list:
    package_info = []

    try:
        # repo_info = session.getRepo(mytag, koji.REPO_STATES["READY"], dist=True)
        # if not repo_info:
        #     print(f"There is no active dist repo for {mytag}")
        # print(repo_info)
        package_info = session.listPackages()
        print(package_info)
    except Exception as e:
        print(e, file=sys.stderr)

    return package_info


def save_to_db(packages: list):
    t = []
    print(f'{len(packages)} packages')
    for package in packages:
        package_id = package.get('package_id')
        package_name = package.get('package_name')
        t.append(koji_package(package_id, package_name))
        # try:
        #     koji_package.objects.create(
        #         package_id=package_id,
        #         package_name=package_name
        #     )
        # except IntegrityError:
        #     pass
    koji_package.objects.bulk_create(t, ignore_conflicts=True, batch_size=100)


if __name__ == '__main__':
    packages = list_packages()
    save_to_db(packages)
